package com.luom.fsp.job.once;

import com.luom.fsp.model.enums.OrderStatusEnum;
import com.luom.fsp.service.OrderService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author 28713
 * 定时任务取消超时订单
 */
@Slf4j
@Component
public class OrderTimeoutOnce {

    @Resource
    private OrderService orderService;

    @PostConstruct
    public void updateTimeoutOrders() {
        // 计算30分钟前的时间
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        LocalDateTime deadlineTime = LocalDateTime.now(zoneId).minusMinutes(30);
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        boolean update = orderService.update()
                .eq("orderStatus", OrderStatusEnum.PENDING.getValue())
                .le("createTime", deadlineTime.format(pattern))
                .set("orderStatus", OrderStatusEnum.CANCELLED.getValue())
                .update();
        if (update) {
            log.info("超时订单已取消");
        }
    }
}
